package com.itboye.jigongbao.db

import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.os.Environment
import com.itboye.jigongbao.R
import com.itboye.jigongbao.app.MyApplication
import com.itboye.jigongbao.bean.CitysBean
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.util.*

/**
 * Created by Administrator on 2018/1/12.
 */
class AddressDbHelper {

    var addressDb: SQLiteDatabase? = null
    val DB_NAME = "itboye.db"
    val DB_PATH = ("/data"
            + Environment.getDataDirectory().absolutePath + "/"
            + MyApplication.instance!!.packageName) // 存放路径;
    private val BUFFER_SIZE = 400000

    companion object {
        var instance: AddressDbHelper? = null
    }

    fun initAddressDB(): SQLiteDatabase? {
        instance = this
        this.addressDb = openDateBase(DB_PATH + "/" + DB_NAME)
        return addressDb
    }

    /**
     * 打开数据库
     *
     * @param dbFile
     * @return SQLiteDatabase
     * @author sy
     */
    private fun openDateBase(dbFile: String): SQLiteDatabase {
        val file = File(dbFile)
        if (!file.exists()) {
            // // 打开raw中得数据库文件，获得stream流
            val stream = MyApplication.instance!!.getResources().openRawResource(
                    R.raw.itboye)
            try {

                // 将获取到的stream 流写入道data中
                val outputStream = FileOutputStream(dbFile)
                val buffer = ByteArray(BUFFER_SIZE)
                var count = 0
                do {
                    count = stream.read(buffer)
                    outputStream.write(buffer, 0, count)
                } while ((count) > 0)
                outputStream.close()
                stream.close()
                return SQLiteDatabase.openOrCreateDatabase(dbFile,
                        null)
            } catch (e: FileNotFoundException) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            } catch (e: IOException) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }


        }
        return this.addressDb!!
    }

    /***
     * 通过省的ID查找下面的市
     * @param
     * @return
     */
    fun getCities(provinceId: String): ArrayList<CitysBean> {
        val arrayCity = ArrayList<CitysBean>()
        var cursor: Cursor? = null
        if (this.addressDb != null)
            cursor = addressDb!!.query("common_city", null, "father like ?", arrayOf(provinceId + "%"), null, null, null)
        if (cursor != null)
            while (cursor.moveToNext()) {
                val citysBean = CitysBean()
                citysBean.setCityName(cursor.getString(cursor.getColumnIndexOrThrow("city")))
                citysBean.setCityId(cursor.getString(cursor.getColumnIndexOrThrow("cityID")))
                citysBean.setProvinceId(cursor.getString(cursor.getColumnIndexOrThrow("father")))
                arrayCity.add(citysBean)
            }
        cursor!!.close()
        addressDb!!.close()
        return arrayCity
    }

    /**
     * 从数据库获取城市数据
     *
     * @return
     */
    fun getProvinces(): ArrayList<CitysBean> {
        val names = ArrayList<CitysBean>()
        val cursor = addressDb!!.rawQuery(
                "select * from common_province", null)
        for (i in 0 until cursor.getCount()) {
            cursor.moveToPosition(i)
            val citysBean = CitysBean()
            citysBean.province = cursor.getString(cursor
                    .getColumnIndex("province"))
            citysBean.provinceId = cursor.getString(cursor
                    .getColumnIndex("provinceID"))
            names.add(citysBean)
        }

        cursor!!.close()
        addressDb!!.close()
        return names
    }

    /***
     * 通过市的ID查找下面的区
     * @param
     * @return
     */
    fun getAreas(cityId: String): ArrayList<CitysBean> {
        val arrayCity = ArrayList<CitysBean>()
        var cursor: Cursor? = null
        if (this.addressDb != null)
            cursor = this.addressDb!!.query("common_area", null, "father like ?", arrayOf(cityId + "%"), null, null, null)
        if (cursor != null)
            while (cursor.moveToNext()) {
                val citysBean = CitysBean()
                citysBean.areaName = cursor.getString(cursor.getColumnIndexOrThrow("area"))
                citysBean.areaId = cursor.getString(cursor.getColumnIndexOrThrow("areaID"))
                citysBean.cityId = cursor.getString(cursor.getColumnIndexOrThrow("father"))
                arrayCity.add(citysBean)
            }
        cursor!!.close()
        addressDb!!.close()
        return arrayCity
    }
}